package com.pomr.service.sys.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pomr.dao.base.BaseDao;
import com.pomr.entity.RoleEntity;
import com.pomr.entity.RoleParam;
import com.pomr.entity.UserEffect;
import com.pomr.model.sys.Effect;
import com.pomr.model.sys.Role;
import com.pomr.model.sys.RoleEffect;
import com.pomr.model.sys.User;
import com.pomr.service.sys.RoleService;
import com.pomr.util.common.CommonData;
import com.pomr.util.common.ResponseData;
import com.pomr.util.page.Page;
import com.pomr.util.page.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * @作者：Administrator
 * @时间：1:34 2018/9/6 0006
 * @用途：
 **/
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    @Qualifier("baseDaoImpl")
    private BaseDao baseDao;

    @Override
    public Page<List<Role>> searchAllRoles(PageParam pageParam) throws Exception {
        String hql = "from Role ";

        Page<List<Role>> p = new Page<>();
        String limit = pageParam.getLimit();
        String page = pageParam.getPage();
        p.setCunrrentPage(new Integer(page));
        p.setPageSize(new Integer(limit));

        return baseDao.showPage(hql, "select count(1) "+hql, p);
    }

    @Override
    public Page<List<Role>> searchRolesLikeName(PageParam pageParam) throws Exception {
        String name = pageParam.getParams().get("sname");
        System.out.println("name:"+name);
        String hql ="from Role";
        if(name != null && !"".equals(name)){
            hql += " where roleName like '%"+name+"%'";
        }

        Page<List<Role>> p = new Page<>();
        String limit = pageParam.getLimit();
        String page = pageParam.getPage();
        p.setCunrrentPage(new Integer(page));
        p.setPageSize(new Integer(limit));

        return baseDao.showPage(hql, "select count(1) "+hql, p);
    }

    @Override
    public List<Effect> searchEffects() throws Exception {
        List<Effect> effect = baseDao.findBySql("select * from effect where patient_id is null and (status != -1 or status is null)", Effect.class);
        for(Effect e: effect){
            String sql = "select * from effect where patient_id = "+e.getId();
            List<Effect> es = baseDao.findBySql(sql, Effect.class);
            e.setChilds(new HashSet<Effect>(es));
        }
        return effect;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertRole(RoleParam roleParam) throws Exception {
        if(roleParam.getRoleName()==null || "".equals(roleParam.getRoleName())){
            throw new Exception("角色名称不能为空");
        }
        Role role = new Role();
        role.setRoleName(roleParam.getRoleName());
        role.setCreateTime(new Date());
        role.setType(2);
        role.setStatus(0);
        role.setRemark(roleParam.getRemark());
        int id = 0;
        if((id = baseDao.addNumKey(role)) > 0){
            //保存角色成功-保存对应权限信息
            List<String> effects = roleParam.getEffects();
            if(effects != null && !effects.isEmpty()){
                for(String eid : effects){
                    RoleEffect re = new RoleEffect();
                    re.setRoleId(id);
                    re.setEffectId(new Integer(eid));
                    if(!baseDao.add(re)){
                        throw new Exception("保存权限信息失败");
                    }
                }
            }
        }else{
            throw new Exception("保存角色信息失败");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRoles(String[] ids) throws Exception {
        if(ids!=null && ids.length>0){
            for(String id:ids){
                //删除角色-权限表信息
                String hql = "delete from RoleEffect where roleId="+id;
                if(!baseDao.editHql(hql)){
                    throw new Exception("删除角色-权限信息失败");
                }
                //TODO 删除用户-角色表信息

                //删除角色信息
                hql = "delete from Role where id="+id;
                if(!baseDao.editHql(hql)){
                    throw new Exception("删除角色信息失败");
                }
            }
        }else{
            return false;
        }
        return true;
    }

    @Override
    public ResponseData seachRoleById(String id) throws Exception {
        if(id==null || "".equals(id)){
            return ResponseData.custom("角色id不能为空");
        }
        String hql = "from Role where id="+id;
        List<Role> roles = baseDao.findByHql(hql);
        if(roles==null || roles.isEmpty()){
            return ResponseData.custom("角色信息未找到");
        }
        Role role = roles.get(0);
        RoleEntity re = new RoleEntity();
        re.setRole(role);
        //获取角色对应权限
        List<RoleEffect> roleEffects = baseDao.findByHql("from RoleEffect where roleId = "+id);
        if(roleEffects!=null){
            re.setRoleEffects(new HashSet<RoleEffect>(roleEffects));
        }
        ResponseData pd = ResponseData.ok();
        pd.putDataValue("role", re);

        return pd;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData editRole(RoleParam roleParam) throws Exception {
        if(roleParam.getId()==null || "".equals(roleParam.getId())){
            return ResponseData.custom("角色id不能为空");
        }
        Role role = new Role();
        role.setId(roleParam.getId());
        role.setStatus(roleParam.getStatus());
        role.setRoleName(roleParam.getRoleName());
        role.setRemark(roleParam.getRemark());
        if(!baseDao.editEntity(role)){
            throw new Exception("更新角色信息失败");
        }
        //更新权限
        baseDao.editHql("delete from RoleEffect where roleId="+roleParam.getId());
        List<String> effects = roleParam.getEffects();
        if(effects != null && !effects.isEmpty()){
            for(String eid : effects){
                RoleEffect roleEffect = new RoleEffect();
                roleEffect.setRoleId(Integer.valueOf(roleParam.getId()));
                roleEffect.setEffectId(Integer.valueOf(eid));
                if(!baseDao.add(roleEffect)){
                    throw new Exception("更新角色权限信息失败");
                }
            }
        }

        return ResponseData.ok();
    }
}
